#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>

int dev_fd = -1;

void async_handler(int signum)
{
    char buffer[128];
    if (dev_fd != -1) {
        int len = read(dev_fd, buffer, sizeof(buffer) - 1);
        if (len > 0) {
            buffer[len] = '\0';
            printf("recv async io signal: %s\n", buffer);
        }
    }
}

int main(int argc, char *argv[])
{
    int fd, oflags;
    fd = open("/dev/fifo", O_RDWR, S_IRUSR | S_IWUSR);
    if (fd !=  - 1)
    {
        dev_fd = fd;
        // 注册异步信号
        signal(SIGIO, async_handler);
        // 设置当前进程捕捉文件信号
        fcntl(fd, F_SETOWN, getpid());
        // 使能异步处理
        oflags = fcntl(fd, F_GETFL);
        fcntl(fd, F_SETFL, oflags | O_ASYNC);
        while(1)
        {
            sleep(100);
        }
    }
    else
    {
        printf("device open failure\n");
    }
}
